package main

import (
	"os"
	"os/signal"
	"smart-flow/monitor/config"
	"smart-flow/monitor/http"
	"smart-flow/monitor/logger"
	"smart-flow/monitor/service"
	"smart-flow/monitor/udp"
	"syscall"
	"time"

	"go.uber.org/zap"
)

var (
	quit chan os.Signal
)

func init() {
	config.LoadConfig("./resource")
	logger.InitLogger(config.AppConfig().Log.LogPath, config.AppConfig().Monitor.Mode)
	config.InitRuntime()
	quit = make(chan os.Signal, 1)
}

func main() {
	logger.Logger.Info("[管控] --- 启动管控服务 ---")
	logger.Logger.Info("[管控] 服务配置", zap.Any("config", config.AppConfig()))
	if !service.RunningContainer(config.HttpStreamPort) {
		return
	}
	var capture *service.Capture
	if config.AppConfig().Monitor.Capture == 1 {
		capture = new(service.Capture)
		if !capture.InitCapture(config.AppConfig().Monitor.InterfaceName) {
			return
		}
	}
	go service.Exchange(capture)
	udpManager := new(udp.ServerManager)
	if !udpManager.Start() {
		logger.Logger.Error("[管控] udp 服务集群启动异常")
		return
	}
	logger.Logger.Info("[管控] udp 服务集群已启动")
	httpManager := new(http.ServerManager)
	if !httpManager.Start() {
		logger.Logger.Error("[管控] http 服务集群启动异常")
		return
	}
	logger.Logger.Info("[管控] http 服务集群已启动")
	signalHandler(httpManager, capture)

}

func signalHandler(httpManager *http.ServerManager, capture *service.Capture) {
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	logger.Logger.Info("[管控] 关闭中...")
	httpManager.Stop()
	logger.Logger.Info("[管控] http 服务集群已关闭")
	time.Sleep(time.Second)
	if capture != nil {
		capture.StopCapture()
		time.Sleep(time.Second)
	}
	logger.Logger.Info("[管控] 已关闭")
}
